package com.lu.log

import android.app.Application
import android.os.Environment
import android.util.Log
import com.dianping.logan.Logan
import com.dianping.logan.LoganConfig
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mars.xlog.Xlog
import xcrash.XCrash
import java.io.File


/**
 * FileName : LogCamp
 * Author : luqihua
 * Date : 2025/3/28
 * Desc : 日志相关模块
 **/

object LogCamp {

    private const val TAG = "LogCamp"

    fun init(application: Application, isDebug: Boolean) {
        Log.d(TAG, "init: isDebug=$isDebug")
        XCrash.init(application)
        initXLog(application, isDebug)
    }


    /**
     * 初始化bugly的crash上报
     */
    private fun initCrashHandler(application: Application, isDebug: Boolean) {
        val userStrategy = CrashReport.UserStrategy(application)
        userStrategy.setCrashHandleCallback(object : CrashReport.CrashHandleCallback() {
            override fun onCrashHandleStart(
                crashType: Int,
                errorType: String?,
                errorMessage: String?,
                errorStack: String?
            ): MutableMap<String, String> {

                return super.onCrashHandleStart(crashType, errorType, errorMessage, errorStack)
            }
        })
        CrashReport.initCrashReport(application, "4111fdde3b", isDebug, userStrategy)
    }


    /**
     * 美团logan的初始化,需要配合服务端一起使用
     */
    private fun initLogan(application: Application, isDebug: Boolean) {
        val logPath = (application.getExternalFilesDir(null)!!.absolutePath
                + File.separator) + "logan_v1"
        Log.d(TAG, "onCreate: logPath=$logPath")
        val config = LoganConfig.Builder()
            .setCachePath(application.filesDir.absolutePath)
            .setPath(logPath)
            .setEncryptKey16("0123456789012345".toByteArray())
            .setEncryptIV16("0123456789012345".toByteArray())
            .build()
        Logan.init(config)
    }


    private fun initXLog(application: Application, isDebug: Boolean) {
        val sdcardDir = Environment.getExternalStorageDirectory().absolutePath;
        val logPath = "$sdcardDir/marssample/log";
        val cachePath = application.filesDir.absolutePath + "/xlog"
        val logLevel = if (isDebug) {
            Xlog.LEVEL_VERBOSE
        } else {
            Xlog.LEVEL_INFO
        }
        //init xlog
        val xlog = Xlog();
        Xlog.open(
            true,
            logLevel,
            Xlog.AppednerModeAsync,
            cachePath,
            logPath,
            "X-LOG",
            "baefcca8d4a3a49f56aecdfd2b03e5edcfae0071fc71e5cd1c4cf19841349347ec8d128c9f25202bd9e59ee7395e182d63ff5da813479acac2b05c886a7853a5"
        )
        com.tencent.mars.xlog.Log.setLogImp(xlog);
        com.tencent.mars.xlog.Log.setConsoleLogOpen(isDebug);
    }

}